package showcase

import (
	"context"
	"strconv"
	"strings"

	"mall/common/ctxdatax"
	"mall/common/enumx"
	"mall/common/resultx"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/rpc/forumclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShowcaseDetailLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewShowcaseDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShowcaseDetailLogic {
	return &ShowcaseDetailLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ShowcaseDetailLogic) ShowcaseDetail(req *types.ShowcaseDetailReq) (resp *types.ShowcaseDetailResp, err error) {
	userId := ctxdatax.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	var filters []string
	if req.UserId > 0 {
		filters = append(filters, "UserId,equalTo:" + strconv.FormatInt(req.UserId, 10))
	} else {
		filters = append(filters, "UserId,equalTo:" + strconv.FormatInt(int64(userId), 10))
	}

	detail, err := l.svcCtx.ForumRpc.ShowcaseDetail(l.ctx, &forumclient.ShowcaseDetailReq{
		Preload:     "forumUserShowcase:Background,Pattern,Frame,Description;forumMedia:Id,Uid,Url,Order",
		EagerLoad:   "forumUserShowcase:forumMedia",
		Filter:      strings.Join(filters, ";"),
		VisitorId:   int64(userId),
		PlatformId:  int32(enumx.ThirdPartyPlatformWechatMini),
	})
	if err != nil {
		return nil, err
	}

	var photos []*types.ForumMedia
	if len(detail.Media) > 0 {
		for _, m := range detail.Media {
			var url string
			if m.Url != "" {
				url = m.Url
			} else {
				url = m.Uri
			}
			photos = append(photos, &types.ForumMedia{
				Uid:      m.Uid,
				Id:       m.Id,
				Url:      url,
				AltText:  m.AltText,
				Details:  m.Meta,
				Order:    m.Order,
			})
		}
	}

	return &types.ShowcaseDetailResp{
		Status:  "ok",
		Message: "",
		Data:    &types.ShowcaseInfo{
			Desc:       detail.Desc,
			Background: detail.Background,
			Pattern:    detail.Pattern,
			Frame:      detail.Frame,
			Photos:     photos,
		},
	}, nil
}
